package com.lxw.nonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxw.nonghe.entity.ChronicDiseaseReimbursement;
import com.lxw.nonghe.entity.Farmer;
import com.lxw.nonghe.mapper.ChronicDiseaseReimbursementMapper;
import com.lxw.nonghe.service.ChronicDiseaseReimbursementService;
import com.lxw.nonghe.service.FarmerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChronicDiseaseReimbursementServiceImpl
        extends ServiceImpl<ChronicDiseaseReimbursementMapper, ChronicDiseaseReimbursement>
        implements ChronicDiseaseReimbursementService {

    @Autowired
    private FarmerService farmerService;
    @Autowired
    private ChronicDiseaseReimbursementMapper chronicDiseaseReimbursementMapper;
    @Override
    public Page<ChronicDiseaseReimbursement> getReimbursementPage(
            int current, int size,
            String farmerName, String diseaseName, String auditStatus) {

        QueryWrapper<ChronicDiseaseReimbursement> wrapper = new QueryWrapper<>();

        // 疾病名称模糊查询
        if (StringUtils.isNotBlank(diseaseName)) {
            wrapper.like("disease_name", diseaseName.trim());
        }

        // 审核状态精确查询
        if (StringUtils.isNotBlank(auditStatus)) {
            wrapper.eq("audit_status", auditStatus.trim());
        }

        // 农民姓名查询优化
        if (StringUtils.isNotBlank(farmerName)) {
            // 使用JOIN方式查询（更高效）
            wrapper.inSql("farmer_id",
                    "SELECT farmer_id FROM t_farmer WHERE name LIKE '%" + farmerName.trim() + "%'");
        }

        // 排序
        wrapper.orderByDesc("reimbursement_time");

        // 执行分页查询
        Page<ChronicDiseaseReimbursement> page = this.page(new Page<>(current, size), wrapper);

        // 补充农民姓名信息
        supplementFarmerNames(page);

        return page;
    }

    @Override
    public Page<ChronicDiseaseReimbursement> queryReimbursements(
            ChronicDiseaseReimbursement queryReimbursement,
            int current, int size) {

        QueryWrapper<ChronicDiseaseReimbursement> wrapper = new QueryWrapper<>();

        // 精确查询条件
        if (queryReimbursement.getFarmerId() != null) {
            wrapper.eq("farmer_id", queryReimbursement.getFarmerId());
        }

        if (queryReimbursement.getInstitutionId() != null) {
            wrapper.eq("institution_id", queryReimbursement.getInstitutionId());
        }

        // 模糊查询条件
        if (StringUtils.isNotBlank(queryReimbursement.getDiseaseName())) {
            wrapper.like("disease_name", queryReimbursement.getDiseaseName().trim());
        }

        // 状态精确查询
        if (StringUtils.isNotBlank(queryReimbursement.getAuditStatus())) {
            wrapper.eq("audit_status", queryReimbursement.getAuditStatus().trim());
        }

        if (StringUtils.isNotBlank(queryReimbursement.getRemittanceStatus())) {
            wrapper.eq("remittance_status", queryReimbursement.getRemittanceStatus().trim());
        }

        // 金额查询（建议使用BigDecimal类型）
        if (queryReimbursement.getReimbursementAmount() != null) {
            wrapper.eq("reimbursement_amount", queryReimbursement.getReimbursementAmount());
        }

        // 排序
        wrapper.orderByDesc("reimbursement_time");

        // 执行分页查询
        Page<ChronicDiseaseReimbursement> page = this.page(new Page<>(current, size), wrapper);

        // 补充农民姓名信息
        supplementFarmerNames(page);

        return page;
    }

    /**
     * 补充农民姓名信息（私有方法复用）
     */
    private void supplementFarmerNames(Page<ChronicDiseaseReimbursement> page) {
        if (!page.getRecords().isEmpty()) {
            Set<Integer> farmerIds = page.getRecords().stream()
                    .map(ChronicDiseaseReimbursement::getFarmerId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            if (!farmerIds.isEmpty()) {
                Map<Integer, String> farmerNameMap = farmerService.listByIds(farmerIds).stream()
                        .collect(Collectors.toMap(Farmer::getFarmerId, Farmer::getName));

                page.getRecords().forEach(reimbursement -> {
                    if (reimbursement.getFarmerId() != null) {
                        reimbursement.setFarmerName(farmerNameMap.get(reimbursement.getFarmerId()));
                    }
                });
            }
        }
    }
    //获取报销金额合计
    @Override
    public BigDecimal getTotalReimbursementAmount() {
        QueryWrapper<ChronicDiseaseReimbursement> wrapper = new QueryWrapper<>();
        return this.list(wrapper).stream()
                .map(ChronicDiseaseReimbursement::getReimbursementAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
    @Override
    public int[] getReimbursementCountByMonth() {
        List<Integer> counts = baseMapper.getReimbursementCountByMonth();
        int[] result = new int[12];
        for(int i = 0;i < counts.size();i++){
            result[i] = counts.get(i);
        }
        return result;
    }
    @Override
    public BigDecimal calculateAnnualReimbursement(Integer farmerId, Integer year) {
        if (farmerId == null || year == null) {
            return BigDecimal.ZERO;
        }

        // 构建当年的开始和结束日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();

        calendar.set(Calendar.MONTH, Calendar.DECEMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endDate = calendar.getTime();

        // 查询当年该农民的所有已通过报销记录的总金额
        LambdaQueryWrapper<ChronicDiseaseReimbursement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChronicDiseaseReimbursement::getFarmerId, farmerId)
                .eq(ChronicDiseaseReimbursement::getAuditStatus, "已通过")
                .between(ChronicDiseaseReimbursement::getReimbursementTime, startDate, endDate);

        // 使用MyBatis-Plus的sum方法计算总金额
        BigDecimal totalAmount = baseMapper.selectList(wrapper).stream()
                .map(ChronicDiseaseReimbursement::getReimbursementAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        return totalAmount != null ? totalAmount : BigDecimal.ZERO;
    }
}
